package com.yao.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.yao.context.BaseContext;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 */

// TODO 关于Spring的IOC注入 与 DI控制，@Autowired的使用 与 控制AliOSSProperties 和该类(AliOSSUtils)的构造函数DI控制(AliOSSProperties) 尚硅谷31级左右
// Error creating bean with name 'uploadController': Unsatisfied dependency expressed through field 'aliOSSUtils'; nested exception is org.springframework.beans.factory.BeanCreationException:
// 创建名为“uploadController”的bean时出错：通过字段“aliOSSUtils”表达的不满足依赖关系；嵌套异常为org.springframework.beans.factory.BeanCreationException：创建文件[F:\code\rear\SpringBoot\bigevent\target\classes\com\yao\\utils\aliOSSUtils.class]中定义的名称为“aliOSSUtils”的bean时出错：
// 重点
// Error creating bean with name 'aliOSSUtils' defined in file [F:\code\rear\SpringBoot\bigevent\target\classes\com\yao\\utils\AliOSSUtils.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.yao.utils.AliOSSUtils]: Constructor threw exception; nested exception is java.lang.NullPointerException: Cannot invoke "com.yao.utils.AliOSSProperties.getAccessKeyId()" because "this.aliOSSProperties" is null
// bean实例化失败；嵌套异常为org.springframework.beans.BeanInstanceException：实例化[com.yao.utils.AliOSSUtils]失败：构造函数引发异常；嵌套异常为java.lang.NullPointerException：无法调用“com.yao.utils.AliOSSProperties.getAccessKeyId（）”，因为“this.AliOSSProperties”为null

@Component
//@AllArgsConstructor
//@NoArgsConstructor
//public class AliOSSUtils {
//
//    @Autowired
//    private AliOSSProperties aliOSSProperties;
//
//    static OSS ossClient;
//    static String bucketName;
//    static String endpoint;
//
//    public AliOSSUtils(){
//        String accessKeyId = aliOSSProperties.getAccessKeyId();
//        String accessKeySecret = aliOSSProperties.getAccessKeySecret();
//        this.bucketName = aliOSSProperties.getBucketName();
//        this.endpoint = aliOSSProperties.getEndpoint();
//        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//
//    }
//
////        String endpoint = aliOSSProperties.getEndpoint();
////        String bucketName = aliOSSProperties.getBucketName();
//
//    /**
//     * 实现上传图片到OSS
//     */
//    public String upload(MultipartFile file) throws IOException {
//        BaseContext.setCurrentId(3);
//
////        String endpoint = aliOSSProperties.getEndpoint();
////        String accessKeyId = aliOSSProperties.getAccessKeyId();
////        String accessKeySecret = aliOSSProperties.getAccessKeySecret();
////        String bucketName = aliOSSProperties.getBucketName();
//
//        // 获取上传的文件的输入流
//        InputStream inputStream = file.getInputStream();
//
//        // 避免文件覆盖
//        String originalFilename = file.getOriginalFilename();
//        String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
//
//        //上传文件到 OSS
////        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//        ossClient.putObject(bucketName, fileName, inputStream);
//
//        //文件访问路径
//        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
//        // 关闭ossClient
//        ossClient.shutdown();
//        return url;// 把上传到oss的路径返回
//    }
//
//    /**
//     * 实现OSS删除图片
//     */
//    public void deleteFile(String url){
////        String endpoint = aliOSSProperties.getEndpoint();
////        String accessKeyId = aliOSSProperties.getAccessKeyId();
////        String accessKeySecret = aliOSSProperties.getAccessKeySecret();
////        String bucketName = aliOSSProperties.getBucketName();
//
////        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//        ossClient.deleteObject(bucketName, url);
//        ossClient.shutdown();
//    }
//
//}

//@Component
//public class AliOSSUtils {
//
//    private AliOSSProperties aliOSSProperties;
//    private OSS ossClient;
//
//    @Autowired
//    public AliOSSUtils(AliOSSProperties aliOSSProperties) {
//        this.aliOSSProperties = aliOSSProperties;
//        String endpoint = aliOSSProperties.getEndpoint();
//        String accessKeyId = aliOSSProperties.getAccessKeyId();
//        String accessKeySecret = aliOSSProperties.getAccessKeySecret();
//        this.ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//    }
//
//    /**
//     * 实现上传图片到OSS
//     */
//    public String upload(MultipartFile file) throws IOException {
//        InputStream inputStream = file.getInputStream();
//        String originalFilename = file.getOriginalFilename();
//        String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
//        ossClient.putObject(aliOSSProperties.getBucketName(), fileName, inputStream);
//        String url = aliOSSProperties.getEndpoint().split("//")[0] + "//" +
//                aliOSSProperties.getBucketName() + "." +
//                aliOSSProperties.getEndpoint().split("//")[1] + "/" + fileName;
//        return url;
//    }
//
//    /**
//     * 实现OSS删除图片
//     */
//    public void deleteFile(String objectName) {
//        ossClient.deleteObject(aliOSSProperties.getBucketName(), objectName);
//    }
//
//    /**
//     * 在应用关闭时关闭 OSSClient
//     */
//    public void closeOSSClient() {
//        ossClient.shutdown();
//    }
//}

public class AliOSSUtils {

    @Autowired
    private AliOSSProperties aliOSSProperties;

    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile file) throws IOException {

        String endpoint = aliOSSProperties.getEndpoint();
//        String accessKeyId = aliOSSProperties.getAccessKeyId();
//        String accessKeySecret = aliOSSProperties.getAccessKeySecret();
        String bucketName = aliOSSProperties.getBucketName();

        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
//        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        OSS ossClient = ossClientInitialize();
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

    /**
     * 实现OSS删除图片
     */
    public void deleteFile(String url){
//        String endpoint = aliOSSProperties.getEndpoint();
//        String accessKeyId = aliOSSProperties.getAccessKeyId();
//        String accessKeySecret = aliOSSProperties.getAccessKeySecret();
        String bucketName = aliOSSProperties.getBucketName();

//        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        OSS ossClient = ossClientInitialize();
        ossClient.deleteObject(bucketName, url);
        ossClient.shutdown();
    }

    public OSS ossClientInitialize(){
        String endpoint = aliOSSProperties.getEndpoint();
        String accessKeyId = aliOSSProperties.getAccessKeyId();
        String accessKeySecret = aliOSSProperties.getAccessKeySecret();
//        String bucketName = aliOSSProperties.getBucketName();

        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

}